﻿
using System;
using System.Threading.Tasks;
using System.Diagnostics;

namespace WSU.ChekaParallel.TestTask
{
    /// <summary>
    /// test the method to start new task
    /// </summary>
    static class TestNoResultTask
    {
        private static void TestFactoryWithoutParm()
        {
            Task.Factory.StartNew(() =>
                {
                    Console.WriteLine("Hello Task From C# in WSU");
                });
            Console.WriteLine("Task has been started.");

            // chekanote: since Task uses pooled threads, which are all background threads
            // we should use "Console.Readline" to prevent main thread, which is foreground, to exit
            // before task is executed
            Console.ReadLine();
        }

        private static void TestFactoryWithParm()
        {
            Task.Factory.StartNew((state) =>
                {
                    Console.WriteLine("Task started with parameter[{0}]", state);
                }, "Cheka");
            Console.ReadLine();// wait for task to be executed
        }

        /// <summary>
        /// test building task manually with action, which has no return value
        /// </summary>
        private static void TestManualTask()
        {
            Task nonStateTask = new Task(() => Console.WriteLine("Build task manually without state"));
            nonStateTask.Start();

            Task stateTask = new Task((state) => Console.WriteLine("Build task manually with state<{0}>", state), "Stasi");
            stateTask.Start();

            Console.ReadLine();
        }

        /// <summary>
        /// Task instance can only be started once, completed task cannot be executed once again
        /// if want to be executed repeatly, you can only create and start a new task with same workload
        /// </summary>
        private static void TestOneshortFeature()
        {
            Task atask = Task.Factory.StartNew((state) =>
                {
                    Console.WriteLine("Task<{0}> executed", state);
                }, "cheka");
            atask.Wait();

            try
            {
                atask.Start();
                Debug.Fail("expecting exceptions");
            }
            catch (InvalidOperationException exp)
            {
                Console.WriteLine("!!!!! Invalid Operation !!!!!");
                Console.WriteLine("Exception = {0}", exp.Message);
            }

            Console.ReadLine();
        }

        public static void TestMain(string[] args)
        {
            // TestFactoryWithoutParm();
            // TestFactoryWithParm();
            // TestManualTask();
            TestOneshortFeature();
        }
    }
}